package com.bhs.sansonglogistics.ui.wallet;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.bean.BusinessInfo;
import com.bhs.sansonglogistics.bean.CardType;
import com.bhs.sansonglogistics.bean.TabBean;
import com.bhs.sansonglogistics.net.NetCallBack;

import com.bhs.sansonglogistics.ui.mine.PersonalInformationActivity;
import com.bhs.sansonglogistics.utils.FastCilckOneUtil;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.gson.Gson;
import com.shouzhong.bankcard.BankCardInfoBean;
import com.shouzhong.scanner.ScannerUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import retrofit2.Response;

/**
 * 添加银行卡
 */
public class AddCardActivity extends BaseActivity implements View.OnClickListener, EasyPermissions.PermissionCallbacks, TextWatcher, NetCallBack {


    private EditText mEtName;
    private EditText mEtCardNumber;
    private FrameLayout mFlPhotograph;
    private Button mBtnSubmit;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    //  private EditText mEtOpeningBank;
    private int bank_type;
    private BusinessInfo businessInfo;
    private TextView mTvTypeBank;
    private List<TabBean> list = new ArrayList<>();
    private int type;

    @Override
    public int initLayout() {
        return R.layout.activity_add_card;
    }

    @Override
    public void initView() {
        bank_type = getIntent().getIntExtra("bank_type", 1);
        businessInfo = getIntent().getParcelableExtra("info");
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("添加银行卡");
        mEtName = findViewById(R.id.et_name);
        mEtCardNumber = findViewById(R.id.et_card_number);
        mFlPhotograph = findViewById(R.id.fl_photograph);
        mFlPhotograph.setOnClickListener(this);
        mBtnSubmit = findViewById(R.id.btn_submit);
        mBtnSubmit.setOnClickListener(this);
        mEtCardNumber.addTextChangedListener(this);
        mEtName.addTextChangedListener(this);
//        mEtOpeningBank = findViewById(R.id.et_opening_bank);
//        mEtOpeningBank.addTextChangedListener(this);
        mTvTypeBank = findViewById(R.id.tv_type_bank);
        mTvTypeBank.setOnClickListener(this);
        type = getIntent().getIntExtra("type", 0);
        mEtName.setText(SharedPreferencesUtils.getString(mContext,"realName"));
        mEtName.setEnabled(false);
    }

    @Override
    public void initData() {
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getData() != null) {
                    String cardNumber = result.getData().getStringExtra("data");
                    mEtCardNumber.setText(cardNumber);
                    //mEtOpeningBank.setText(result.getData().getStringExtra("bank_name"));
                }
            }
        });
        networkRequest(netApi.get_bank_list(), this, 888);
    }

    @Override
    public void onClick(View view) {
        if (FastCilckOneUtil.isFastClick()) {
            return;
        }
        if (view.getId() == R.id.fl_photograph) {
            methodRequiresTwoPermission();
        } else if (view.getId() == R.id.btn_submit) {
            confirm();
        } else if (view.getId() == R.id.tv_type_bank) {
            bottomSelect();
        }
    }

    private void bottomSelect() {
        if (MyUtils.isEmpty(list)) {
            ToastUtil.show("正在获取数据");
            return;
        }
        if (pvOptions == null) {
            pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int option2, int options3, View v) {
                    mTvTypeBank.setText(list.get(options1).getTypeName());
                    mTvTypeBank.setTag(list.get(options1).getType());
                }
            }).build();
            pvOptions.setPicker(list);
        }
        pvOptions.show();

    }

    private OptionsPickerView<TabBean> pvOptions;

    private void confirm() {
        if (!MyUtils.checkBankCard(mEtCardNumber.getText().toString())) {
            ToastUtil.show("请输入正确的银行卡");
            return;
        }
        loadingPopupShow();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> map = new ArrayMap<>();
                BankCardInfoBean bean = ScannerUtils.getBankCardInfo(mEtCardNumber.getText().toString());
                map.put("bank_name", BankCardInfoBean.getCNBankName(bean.bank));
                map.put("bank_card_type", MyUtils.getCNCardTypeName(BankCardInfoBean.getCNCardType(bean.cardType)));
                map.put("bank_type", String.valueOf(bank_type));
                map.put("bank_truename", mEtName.getText().toString());
                map.put("bank_number", mEtCardNumber.getText().toString());
                map.put("bank_code", (String) mTvTypeBank.getTag());
                if (bank_type == 2) {
                    map.put("company_name", businessInfo.company_name);
                    map.put("company_lisence_pic", businessInfo.company_lisence_pic);
                    map.put("company_lisence_no", businessInfo.company_lisence_no);
                    map.put("company_address", businessInfo.company_address);
                    map.put("legal_truename", businessInfo.legal_truename);
                    map.put("legal_card_front", businessInfo.legal_card_front);
                    map.put("legal_card_back", businessInfo.legal_card_back);
                    map.put("legal_card_no", businessInfo.company_lisence_no);
                    map.put("legal_mobile", businessInfo.legal_mobile);
                }
                networkRequest(netApi.add_bank(map), AddCardActivity.this);
            }
        }).start();

    }

    public void goPage() {
        Intent intent = new Intent(mActivity, ScanActivity.class);
        intentActivityResultLauncher.launch(intent);
    }

    public static final int RC_LOCATION = 1; // requestCode
    String[] perms = {Manifest.permission.CAMERA};

    @AfterPermissionGranted(RC_LOCATION)
    private void methodRequiresTwoPermission() {
        if (EasyPermissions.hasPermissions(this, perms)) {
            goPage();
        } else {
            // Do not have permissions, request them now
            EasyPermissions.requestPermissions(this, "我需要您的位置信息来获取当前地址",
                    RC_LOCATION, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        LogUtils.d("????");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("提示").setRationale("此功能需要开通权限，请转到设置相机权限").build().show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {

        }

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        verify();
    }

    private void verify() {
        boolean verify = true;
        if (TextUtils.isEmpty(mEtName.getText())) {
            verify = false;
        }
        if (TextUtils.isEmpty(mEtCardNumber.getText())) {
            verify = false;
        }
//        if (TextUtils.isEmpty(mEtOpeningBank.getText())) {
//            verify = false;
//        }
        mBtnSubmit.setEnabled(verify);
        mBtnSubmit.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 888) {
            CardType cardType = new Gson().fromJson(json, CardType.class);
            if (cardType.getCode().equals("1")) {
                for (CardType.DataDTO.ListDTO listDTO : cardType.getData().getList()) {
                    list.add(new TabBean(listDTO.getName(), listDTO.getCode()));
                }
            }
        } else {
            loadingPopupDismiss();
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            ToastUtil.show(bean.getMsg());
            if (bean.isStatus()) {
                finish();
                if (type == 0) {
                    startActivity(new Intent(mActivity, BankCardActivity.class));
                }
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {
        loadingPopupDismiss();
    }
}